package com.base.cn.platform.os.service.course.mould;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.service.CommonSetCreateUserDataService;
import com.base.cn.platform.os.common.service.CommonSetSubjectDataService;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.course.mould.CouMouldDao;
import com.base.cn.platform.os.entity.course.mould.CouMould;
import com.base.cn.platform.os.entity.course.mould.CouMouldCondition;
import com.base.cn.platform.os.entity.course.mould.CouMouldMaterial;
import com.base.cn.platform.os.service.manage.subject.SubjectService;
import com.base.cn.platform.os.service.manage.sysUser.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模块biz
 *
 * @author s.li
 * @create 2018-04-23-18:20
 */
@Service
public class CouMouldBiz extends BaseBiz<CouMould,CouMouldDao> {
    @Autowired
    private CommonSetSubjectDataService<CouMould> commonSetSubjectDataService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private CommonSetCreateUserDataService<CouMould> commonSetCreateUserDataService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CouMouldMaterialBiz couMouldMaterialBiz;
    @Autowired
    private CouMouldDao couMouldDao;

    /**
     * 查询模块数量
     * @param condition
     * @return 数量
     */
    public BigDecimal mouldCount(CouMouldCondition condition){
        return this.count(this.getWhereSql(condition));
    }

    /**
     * 保存模块数据
     * @param couMould 模块数据对象
     * @return  CouMould
     */
    public CouMould saveMould(CouMould couMould){
        if(DataUtil.idIsNotNull(couMould.getId())){//修改
            CouMould mould = this.findById(couMould.getId());
            mould.setMouldName(couMould.getMouldName());
            mould.setSubjectIds(couMould.getSubjectIds());
            mould.setMaterialNum(couMould.getMaterialNum());

            if(couMould.getMouldType().intValue()==1){//如果是公有
                mould.setSysUserId(new BigDecimal(0));
            }else{
                //原来是公有，修改成私有，则要设置拥有人的ID
                if(mould.getMouldType().intValue()==1 && couMould.getMouldType().intValue()==2){
                    mould.setSysUserId(couMould.getCreateUserId());
                }
            }
            mould.setMouldType(couMould.getMouldType());
            this.updateById(mould,null);
            return mould;
        }else{//添加
            couMould.setStatus(1);
            couMould.setFinish(1);
            if(couMould.getMouldType().intValue()==2){//如果是私有的
                couMould.setSysUserId(couMould.getCreateUserId());//设置拥有人的ID
            }
            this.save(couMould);
        }
        return couMould;
    }

    /**
     * 修改模块状态
     * @param updateList 要修改列表
     * @param deleteList 要删除的列表
     * @param status 状态，1未发布，2已发布，3隐藏，
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void updateCouMouldStatus(List<CouMould> updateList,List<CouMould> deleteList,int status){
        String deleteIds = "";
        String updateIds = "";
        if(ObjectUtils.isNotEmpty(updateList)){
            updateIds = updateList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
        }
        if(ObjectUtils.isNotEmpty(deleteList) && status==4){
            deleteIds = deleteList.stream().map(e->e.getId().toString()).collect(Collectors.joining(","));
        }
        //真删除
        if(StringUtils.isNotEmpty(deleteIds)){
            this.deleteWhereSql(" id in ("+deleteIds+")");
        }
        //修改状态
        if(StringUtils.isNotEmpty(updateIds)){
            CouMould mould = new CouMould();
            if(status==5){
                status =2;
            }
            mould.setStatus(status);
            this.updateByWhereSql(mould," id in ("+updateIds+")");
        }
    }
    /**
     * 修改模块为完成状态
     * @param ids 模块ID串
     */
    public void updateMouldFinishStatus(String ids){
        if(StringUtils.isNotEmpty(ids)){
            ids = StringUtils.subHeadTailString(ids,",");
            if(StringUtils.isNotEmpty(ids)){
                CouMould mould =new CouMould();
                mould.setFinish(2);
                this.updateByWhereSql(mould," id in ("+ids+")");
            }
        }
    }
    /**
     * 通过ID查询模块对象数据
     * @param id
     * @param subjectData
     * @param createUserData
     * @param materialData
     * @return
     */
    public CouMould findCouMouldById(BigDecimal id,
                                     boolean subjectData,boolean createUserData,boolean materialData){
        if(DataUtil.idIsNotNull(id)){
            List<CouMould> couMouldList = this.findCouMouldByIds(id.toString(),subjectData,createUserData,materialData);
            if(ObjectUtils.isNotEmpty(couMouldList)){
                return couMouldList.get(0);
            }
        }
        return null;
    }

    /**
     * 通过ID串，查询模块列表
     * @param ids
     * @param subjectData
     * @param createUserData
     * @param materialData
     * @return
     */
    public List<CouMould> findCouMouldByIds(String ids,
                                            boolean subjectData,boolean createUserData,boolean materialData){
        CouMouldCondition couMouldCondition = new CouMouldCondition();
        couMouldCondition.setQueryIds(ids);
        return  this.findCouMouldList(couMouldCondition,subjectData,createUserData,materialData);
    }

    /**
     * 多条件是查询模块列表
     * @param condition 查询条件
     * @return List<CouMould>
     */
    public List<CouMould> findCouMouldList(CouMouldCondition condition,
                                           boolean subjectData,boolean createUserData,boolean materialData){
        String whereSql = this.getWhereSql(condition);
        List<CouMould> couMouldList = this.find(whereSql,condition.getCount(),null);
        couMouldList = this.setMouldExData(couMouldList,subjectData,createUserData,materialData);
        return couMouldList;
    }

    /**
     * 分页查询模块数据
     * @param condition
     * @param page
     * @param subjectData
     * @param createUserData
     * @param materialData
     * @return
     */
    public PageInfo<CouMould> findCouMouldPage(CouMouldCondition condition,
                                               Pagination page,
                                               boolean subjectData,boolean createUserData,boolean materialData){
        PageInfo<CouMould> couMouldPageInfo  = null;
        if(condition.getType()==1){
            if(StringUtils.isNotEmpty(condition.getSubjectIds())){
                String subjectSql = StringUtils.getSubjectSql("CouMould.subjectIds",condition.getSubjectIds());
                condition.setSubjectSql(subjectSql);
            }
            couMouldPageInfo = findCourseToMouldList(condition,page);
        }else{
            couMouldPageInfo = this.findPage(this.getWhereSql(condition),page,null);
        }
        this.setMouldExData(couMouldPageInfo.getList(),subjectData,createUserData,materialData);
        return couMouldPageInfo;
    }

    /**
     * 查询课程可以选择的模块数据列表
     * @param condition 查询条件
     * @return PageInfo<CouMould>
     */
    private PageInfo<CouMould> findCourseToMouldList(CouMouldCondition condition,Pagination page){
        PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        Page<CouMould> couMouldPage = couMouldDao.findCourseToMouldList(CouMould.class,condition);
        PageInfo<CouMould> couMouldPageInfo = new PageInfo<>(couMouldPage);
        return couMouldPageInfo;
    }

    //---------------------=================================

    /**
     * 设置模块扩展数据
     * @param couMouldList
     * @param subjectData
     * @param createUserData
     * @param materialData
     * @return List<CouMould>
     */
    private List<CouMould> setMouldExData(List<CouMould> couMouldList,boolean subjectData,boolean createUserData,boolean materialData){
        if(ObjectUtils.isNotEmpty(couMouldList)){
            if(subjectData){//查询专业数量
                couMouldList = commonSetSubjectDataService.setSubjectData(subjectService,couMouldList,subjectData);
            }
            if(createUserData){//查询创建人数据
                couMouldList = commonSetCreateUserDataService.setSysUserData(sysUserService,couMouldList,createUserData);
            }
            if(materialData){//查询素材数据
                couMouldList = setMaterialData(couMouldList,materialData);
            }
        }
        return couMouldList;
    }

    /**
     * 设置素材数据
     * @param couMould
     * @param materialData
     * @return CouMould
     */
    private CouMould setMaterialData(CouMould couMould , boolean materialData){
        if(ObjectUtils.isNotEmpty(couMould) && materialData){
            List<CouMould> couMouldList = new ArrayList<>();
            couMouldList.add(couMould);
            couMouldList = this.setMaterialData(couMouldList,materialData);
            couMould = couMouldList.get(0);
        }
        return couMould;
    }

    /**
     * 设置素材数据
     * @param couMouldList
     * @param materialData
     * @return List<CouMould>
     */
    private List<CouMould> setMaterialData(List<CouMould> couMouldList,boolean materialData){
        if(ObjectUtils.isNotEmpty(couMouldList) && materialData){
            Map<BigDecimal,List<CouMouldMaterial>> couMouldMaterialListMaps = couMouldMaterialBiz.getMouldToMaterialMap(couMouldList.stream().map(e->e.getId().toString()).collect(Collectors.joining(",")));
            if(ObjectUtils.isNotEmpty(couMouldMaterialListMaps)){
                couMouldList.forEach(e->{
                    List<CouMouldMaterial> couMouldMaterialList = couMouldMaterialListMaps.get(e.getId());
                    e.setCouMouldMaterialList(couMouldMaterialList);
                });
            }
        }
        return couMouldList;
    }

    /**
     * 获取查询条件
     * @param condition
     * @return
     */
    private String getWhereSql(CouMouldCondition condition){
        //查询所有公有的模块
        StringBuilder whereSql = new StringBuilder( " status!=4 and (mouldType=1 or mouldType=2)");
        if(ObjectUtils.isNotEmpty(condition)){
            if(StringUtils.isNotEmpty(condition.getSubjectIds())){
                whereSql .append( StringUtils.getSubjectSql("subjectIds",condition.getSubjectIds()));
            }
            if(StringUtils.isNotEmpty(condition.getMouldName())){
                whereSql .append(" and mouldName like '%").append(condition.getMouldName().trim()).append("%'");
            }
            if(condition.getStatus()!=null){
                whereSql .append(" and status = ").append(condition.getStatus());
            }

            if(condition.getFinish()!=null){
                whereSql .append(" and finish=").append(condition.getFinish());
            }
            if(DataUtil.idIsNotNull(condition.getSysUserId())){
                whereSql .append(" and (sysUserId=").append(condition.getSysUserId()).append(" or sysUserId = 0)");
            }
            if(StringUtils.isNotEmpty(condition.getQueryIds())){
                whereSql .append(" and id in (").append(condition.getQueryIds()).append(")");
            }
        }
        whereSql .append(" order by createTime desc");
        return whereSql.toString();
    }
}
